/*******************************************************
> Copyright (C) 2024 ==IOT== All rights reserved.
> File Name: string.cpp
> Author: IOT
> Website:www.slq.org
> Created Time: 2024年10月22日 星期二 16时14分05秒
***************************************************/

#include <iostream>
#include <cstring>

using namespace std;

class String {
	public:
	char *buf;
	int len;
	
	public:
		String() : buf(nullptr),len(0)
		{}
		String(const char *src)
		{
			len = strlen(src);
			buf = new char[len + 1]; // new 在分配空间时会自动赋0
			strcpy(buf, src);
		}
		
		String(const String &obj) // 拷贝构造
		{
			cout << "copy construcor call" << endl;	
			len = strlen(obj.buf);	
			this->buf = new char[len + 1];
			strcpy(this->buf, obj.buf); // 深拷贝，完全拷贝(数据部分)
			

		}

		~String()
		{
			if (buf != nullptr) {
				delete [] buf;
			}
		}
		
		bool operator==(const char *src)
		{
			return strcmp(this->buf, src) == 0 ? true : false;
		}
		bool operator==(String &str)
		{
			return strcmp(this->buf, str.buf) == 0 ? true : false;
		}
		
		bool operator>(String &str)
		{
			return strcmp(this->buf, str.buf) > 0 ? true : false;
		}
		bool operator<(String &str)
		{
			return strcmp(this->buf, str.buf) < 0 ? true : false;
		}
		bool operator!=(String &str)
		{
			return strcmp(this->buf, str.buf) != 0 ? true : false;
		}

		// 赋值运算符(=)重载， m = n
		String& operator=(const String str)
		{
			cout << "str addr" << &str << endl;
			delete [] this->buf;
			
			// this-> buf = str.buf; // 浅拷贝(copy),指针复制
			
			this->buf = new char[strlen(str.buf) + 1];
			strcpy(this->buf, str.buf); // 深拷贝，完全拷贝(数据部分)
			
			return *this;
		}

		void operator+=(String &str)
		{
			String temp;
			temp.buf = new char[this->len + 1]; // new 在分配空间时会自动赋0
			strcpy(temp.buf, this->buf);

			this->len += str.len;
			delete []this->buf;
			
			this->buf = new char[this->len + 1]; 	
			strcpy(this->buf, temp.buf);
			strcat(this->buf, str.buf);		
		}

		//String operator+();
		
		//find(char c); // 查找字符
		char *find(const char *src)
		{
			return strstr(this->buf, src);
		}
		
		char *find(String &str)
		{
			return strstr(this->buf, str.buf);	
		}
		
		String substr(int pos, int len) // 提取子串
		{
			String temp;
			cout << "temp addr:" << &temp << endl;
			temp.buf = new char[len + 1]; // new 在分配空间时会自动赋0
		
			strncpy(temp.buf, &this->buf[pos], len);
			cout << temp.buf << endl; // debug
		
			return  temp; // no call
			//return *this; // call copy constructor
		}
		void show()
		{
			cout << buf << endl;
		}
};


int main(int argc,const char* argv[])
{
	String name1("lucy");
	String name3("hh");

	//error: double free	
	//name3 = name1.substr(0, 2);

	//name1.substr(0, 2);

	name1 = name3;
	//name3.operator=(name1.substr(0,2));

	cout << name3.buf << endl;		

    return 0;
}
